<template>
  <!-- 新增工作票 表单 -->
  <a-modal
    v-model:open="visible"
    title="新增工作票"
    @ok="handleOk"
    class="addStation"
    destroyOnClose
    :width="850"
    @cancel="cancel"
    centered
  >
    <a-form
      :model="form"
      :rules="rules"
      layout="inline"
      :labelCol="labelCol"
      ref="formRef"
    >
      <a-form-item label="电站名称" name="stationId">
        <a-select
          v-model:value="form.stationId"
          placeholder="请选择"
          allow-clear
          show-search
          optionFilterProp="label"
          style="width: 250px"
          :disabled="props.addType === 1"
          @change="getCompanyName"
        >
          <a-select-option
            v-for="item in stationtList"
            :value="item.stationId"
            :key="item.stationId"
            :label="item.stationName"
          >
            {{ item.stationName }}
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="关联工单编号" name="" v-if="props.addType === 1">
        <a-input
          v-model:value="form.workOrderSerialCode"
          class="formInput"
          placeholder="请输入"
          disabled
        />
      </a-form-item>
      <a-form-item label="作业项目" name="companyName">
        <a-input
          v-model:value="form.companyName"
          class="formInput"
          placeholder="请输入"
          disabled
        />
      </a-form-item>
      <a-form-item label="作业日期" name="operationDate">
        <a-date-picker
          v-model:value="form.operationDate"
          class="formInput"
          value-format="YYYY-MM-DD"
          format="YYYY-MM-DD"
        />
      </a-form-item>
      <a-form-item label="作业时段" name="operationTime">
        <a-time-range-picker
          v-model:value="form.operationTime"
          class="formInput"
          value-format="HH:mm"
          format="HH:mm"
          separator="~"
          showTime
          allowClear
        />
      </a-form-item>
      <a-form-item label="作业地点" name="operationAddress">
        <a-input
          v-model:value="form.operationAddress"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>
      <a-form-item label="作业内容描述" name="operationRemark">
        <a-textarea
          v-model:value="form.operationRemark"
          class="formInput"
          placeholder="请输入"
          :rows="4"
          style="width: 634px"
        />
      </a-form-item>
      <a-form-item>
        <template v-slot:label>
          <span class="my-custom-label">受影响相关方</span>
          <a-tooltip>
            <template #title
              >受影响相关方填写为：设备厂商售后人员、其他参与到本次故障处理的人员等</template
            >
            <ExclamationCircleOutlined class="ExclamationCircleOutlined" />
          </a-tooltip>
        </template>
        <a-input
          v-model:value="form.affectedStakeholders"
          class="formInput"
          placeholder="请输入"
        />
      </a-form-item>

      <a-form-item label="安全工作方案">
        <a-upload
          v-model:file-list="fileList[0]"
          name="file"
          accept=".JPEG,.JPG,.PNG"
          :max-count="1"
          :action="uploadUrl"
          :headers="headers"
          method="post"
          :preview-file="previewFile"
          :before-upload="beforeUpload"
          @change="(res) => handleUploadChange(res, 'safetyPlanFileIds')"
          @remove="handleRemove('safetyPlanFileIds')"
        >
          <div class="formInput">
            <a-button type="link" class="uploadBtn">点击上传附件</a-button>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="图纸">
        <a-upload
          v-model:file-list="fileList[1]"
          name="file"
          accept=".JPEG,.JPG,.PNG"
          :max-count="1"
          :action="uploadUrl"
          :headers="headers"
          method="post"
          :preview-file="previewFile"
          :before-upload="beforeUpload"
          @change="(res) => handleUploadChange(res, 'drawingFileIds')"
          @remove="handleRemove('drawingFileIds')"
        >
          <div class="formInput">
            <a-button type="link" class="uploadBtn">点击上传附件</a-button>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item>
        <template v-slot:label>
          <span class="my-custom-label">其它附件</span>
          <a-tooltip>
            <template #title>危害识别、特殊说明等</template>
            <ExclamationCircleOutlined class="ExclamationCircleOutlined" />
          </a-tooltip>
        </template>
        <a-upload
          v-model:file-list="fileList[2]"
          name="file"
          accept=".JPEG,.JPG,.PNG"
          :max-count="1"
          :action="uploadUrl"
          :headers="headers"
          method="post"
          :preview-file="previewFile"
          :before-upload="beforeUpload"
          @change="(res) => handleUploadChange(res, 'otherAttachFileIds')"
          @remove="handleRemove('otherAttachFileIds')"
        >
          <div class="formInput">
            <a-button type="link" class="uploadBtn">点击上传附件</a-button>
          </div>
        </a-upload>
      </a-form-item>
      <a-form-item label="图纸说明">
        <a-input
          v-model:value="form.drawingDesc"
          class="formInput"
          placeholder="请输入"
          style="width: 634px"
        />
      </a-form-item>
      <a-form-item label="工作类型判定" name="workTypeList">
        <div class="tableBox">
          <div class="checkItem" v-for="item in workTypeList" :key="item.name">
            <a-form-item-rest>
              <a-checkbox
                v-model:checked="item.value"
                @change="() => formRef.validateFields('workTypeList')"
              >
                {{ item.label }}
              </a-checkbox>
            </a-form-item-rest>
          </div>
        </div>
      </a-form-item>
      <a-form-item name="harmList">
        <template v-slot:label>
          <span class="my-custom-label">危害识别</span>
          <a-tooltip>
            <template #title
              >工艺设备、作业工具、作业地点是否存在下列危险</template
            >
            <ExclamationCircleOutlined class="ExclamationCircleOutlined" />
          </a-tooltip>
        </template>
        <div class="tableBox">
          <div
            class="checkItem"
            v-for="item in harmList.filter(
              (item) => item.name !== 'otherHazardDescription'
            )"
            :key="item.name"
          >
            <a-form-item-rest>
              <a-checkbox
                v-model:checked="item.value"
                @change="() => formRef.validateFields('harmList')"
              >
                {{ item.label }}
              </a-checkbox>
            </a-form-item-rest>
          </div>
          <div
            v-if="harmList[harmList.length - 2]?.value"
            style="width: 240px"
            class="otherInput"
          >
            <a-form-item
              :rules="{
                required: true,
                trigger: 'blur',
                validator: errorMsgRule(harmList[harmList.length - 1].value),
              }"
              :name="`value`"
            >
              <a-input
                v-model:value="harmList[harmList.length - 1].value"
                placeholder="请输入"
                size="small"
                style="width: 240px"
              />
            </a-form-item>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="工作前安全措施" name="deviceList">
        <div class="tableBox">
          <div
            class="checkItem"
            v-for="item in deviceList.filter(
              (item) => item.name !== 'otherSafetyMeasuresDescription'
            )"
            :key="item.name"
            style="width: 33.33%"
          >
            <a-form-item-rest>
              <a-checkbox
                v-model:checked="item.value"
                @change="() => formRef.validateFields('deviceList')"
              >
                {{ item.label }}
              </a-checkbox>
            </a-form-item-rest>
          </div>
          <div
            v-if="deviceList[deviceList.length - 2]?.value"
            style="width: 200px"
            class="otherInput"
          >
            <a-form-item
              :rules="{
                required: true,
                trigger: 'blur',
                validator: errorMsgRule(
                  deviceList[deviceList.length - 1].value
                ),
              }"
              :name="`value`"
            >
              <a-input
                v-model:value="deviceList[deviceList.length - 1].value"
                placeholder="请输入"
                size="small"
                style="width: 100%"
              />
            </a-form-item>
          </div>
        </div>
      </a-form-item>
      <a-form-item label="个人防护装备" name="protectEquipment">
        <div class="tableBox">
          <div
            class="checkItem"
            v-for="item in protectEquipment.filter(
              (item) =>
                item.name !== 'otherPersonalProtectiveEquipmentDescription'
            )"
            :key="item.name"
            style="width: 33.33%"
          >
            <a-form-item-rest>
              <a-checkbox
                v-model:checked="item.value"
                @change="() => formRef.validateFields('protectEquipment')"
              >
                {{ item.label }}
              </a-checkbox>
            </a-form-item-rest>
          </div>
        </div>
        <div
          v-if="protectEquipment[protectEquipment.length - 2]?.value"
          style="width: 634px"
          class="otherInput"
        >
          <a-form-item-rest
            :rules="{
              required: true,
              trigger: 'blur',
              validator: errorMsgRule(
                protectEquipment[protectEquipment.length - 1].value
              ),
            }"
            :name="`value`"
          >
            <a-input
              v-model:value="
                protectEquipment[protectEquipment.length - 1].value
              "
              placeholder="请输入"
              size="small"
              style="width: 100%"
            />
          </a-form-item-rest>
        </div>
      </a-form-item>
    </a-form>
    <template #footer>
      <div class="footerBar">
        <a-button key="back" @click="cancel">取消</a-button>
        <a-button
          key="submit"
          type="primary"
          :loading="loading"
          @click="handleSubmit"
          >确认</a-button
        >
      </div>
    </template>
  </a-modal>
</template>
<script setup>

import storage from "@/utils/storage"
import {
  WORK_TYPE_LIST,
  HARM_LIST,
  DEVICE_LIST,
  PROTECT_EQUIPMENT,
} from "@/constants/workOrder"
import { add, cloneDeep, rest } from "lodash-es"
import moment from "moment"
const $api = inject("$api")
const props = defineProps({
  addTicketVisible: {
    type: Boolean,
    default: false,
  },
  rowData: {
    type: Object,
  },
  ticketRowData: {
    type: Object,
  },
  infoData: {
    type: Object,
  },
  stationtList: {
    type: Array,
  },
  orderPageType: {
    type: String,
  },
  isCopy: {
    type: Boolean,
  },
  addType: {
    type: Number,
    default: 1, // 1 关联工单 2 不关联工单
  },
})
const visible = ref(props.addTicketVisible)
const emits = defineEmits(["update:addTicketVisible", "getOrderList"])
const fileList = ref([])
const userInf = storage.getItem("USER_INFO")
const headers = ref({
  Authorization: "Bearer " + userInf.access_token,
})
const getCompanyName = async (val) => {
  form.value.companyName = props.stationtList.find(
    (item) => item.stationId === val
  )?.companyName
}
watch(
  () => props.addTicketVisible,
  async (val) => {
    visible.value = val
    if (val) {
      workTypeList.value = cloneDeep(WORK_TYPE_LIST)
      harmList.value = cloneDeep(HARM_LIST)
      deviceList.value = cloneDeep(DEVICE_LIST)
      protectEquipment.value = cloneDeep(PROTECT_EQUIPMENT)
      form.value.stationId = props.rowData?.stationId
      form.value.workOrderSerialCode = props.rowData?.serialCode
      form.value.companyName = props.rowData?.companyName
      if (props.isCopy) {
        initForm()
      }
    }
  }
)
const labelCol = { style: { width: "120px" } }
const formRef = ref(null)
const form = ref({
  stationId: undefined,
  workOrderSerialCode: undefined,
  companyName: undefined,
  operationDate: undefined,
  operationTime: undefined,
  operationLocation: undefined,
  operationRemark: undefined,
  affectedStakeholders: undefined,
  drawingDesc: undefined,
  workType: undefined, // 工作类型判定
  workTypeOther: undefined, // 工作类型判定 其它说明
  hazardIdentification: undefined, // 危害识别
  hazardIdentificationOther: undefined, // 危害识别 其它说明
  workSafetyMeasure: undefined, // 工作安全措施
  workSafetyMeasureOther: undefined, // 工作安全措施 其它说明
  protectiveEquipment: undefined, // 保护设备
  protectiveEquipmentOther: undefined, // 保护设备 其它说明
  safetyPlanFileIds: undefined,
  drawingFileIds: undefined,
  otherAttachFileIds: undefined,
})
const rules = ref({
  stationId: [
    {
      required: true,
      message: "请选择电站",
      trigger: "blur",
    },
  ],
  workOrderSerialCode: [
    {
      required: true,
      message: "请输入工单编号",
      trigger: "blur",
    },
  ],
  companyName: [
    {
      required: true,
      message: "请输入作业项目",
      trigger: "blur",
    },
  ],
  operationDate: [
    {
      required: true,
      message: "请选择作业日期",
      trigger: "blur",
    },
  ],
  operationTime: [
    {
      required: true,
      message: "请选择作业时间",
      trigger: "change",
    },
  ],
  operationAddress: [
    {
      required: true,
      message: "请输入作业地点",
      trigger: "blur",
    },
  ],
  operationRemark: [
    {
      required: true,
      message: "请输入作业内容描述",
      trigger: "blur",
    },
  ],
  workTypeList: [
    {
      required: true,
      trigger: "change",
      validator: () => {
        const hasChecked = workTypeList.value.some((item) => item.value)
        if (!hasChecked) {
          return Promise.reject("请至少选择一个工作类型判定")
        }
        return Promise.resolve()
      },
    },
  ],
  harmList: [
    {
      required: true,
      trigger: "change",
      validator: () => {
        const hasChecked = harmList.value.some((item) => item.value)
        if (!hasChecked) {
          return Promise.reject("请至少选择一个危害因素")
        }
        return Promise.resolve()
      },
    },
  ],
  deviceList: [
    {
      required: true,
      trigger: "change",
      validator: () => {
        const hasChecked = deviceList.value.some((item) => item.value)
        if (!hasChecked) {
          return Promise.reject("请至少选择一个设备")
        }
        return Promise.resolve()
      },
    },
  ],
  protectEquipment: [
    {
      required: true,
      trigger: "change",
      validator: () => {
        const hasChecked = protectEquipment.value.some((item) => item.value)
        if (!hasChecked) {
          return Promise.reject("请至少选择一个个人防护装备")
        }
        return Promise.resolve()
      },
    },
  ],
})
const workTypeList = ref([])
const harmList = ref([])
const deviceList = ref([])
const protectEquipment = ref([])
//清空表单
const resetForm = () => {
  // 重置表单数据
  form.value = {
    stationId: undefined,
    workOrderSerialCode: undefined,
    companyName: undefined,
    operationDate: undefined,
    operationTime: undefined,
    operationLocation: undefined,
    operationRemark: undefined,
    affectedStakeholders: undefined,
    drawingDesc: undefined,
    workType: undefined, // 工作类型判定
    workTypeOther: undefined, // 工作类型判定 其它说明
    hazardIdentification: undefined, // 危害识别
    hazardIdentificationOther: undefined, // 危害识别 其它说明
    workSafetyMeasure: undefined, // 工作安全措施
    workSafetyMeasureOther: undefined, // 工作安全措施 其它说明
    protectiveEquipment: undefined, // 保护设备
    protectiveEquipmentOther: undefined, // 保护设备 其它说明
    safetyPlanFileIds: undefined,
    drawingFileIds: undefined,
    otherAttachFileIds: undefined,
  }
  fileList.value = []
}
const cancel = () => {
  emits("update:addTicketVisible", false)
  formRef.value.clearValidate()
  resetForm()
}
const loading = ref(false)
const mapListToParams = (data) => {
  // 找出当前组内勾选项的索引
  const indexes = Object.entries(data)
    .map(([, value], index) => (value.value ? index : -1))
    .filter((index) => index !== -1)
    .join(",")
  return indexes
}

const handleSubmit = () => {
  formRef.value
    .validate()
    .then(async () => {
      const { operationTime, ...rest } = form.value
      const params = {
        ...rest,
        orderId: props.infoData?.id,
        operationStartDate: form.value.operationTime[0],
        operationEndDate: form.value.operationTime[1],

        workType: mapListToParams(workTypeList.value),
        workTypeOther: workTypeList.value[workTypeList.value.length - 1].value,

        hazardIdentification: mapListToParams(harmList.value),
        hazardIdentificationOther:
          harmList.value[harmList.value.length - 1].value,

        workSafetyMeasure: mapListToParams(deviceList.value),
        workSafetyMeasureOther:
          deviceList.value[deviceList.value.length - 1].value,

        protectiveEquipment: mapListToParams(protectEquipment.value),
        protectiveEquipmentOther:
          protectEquipment.value[protectEquipment.value.length - 1].value,
      }
      loading.value = true
      const res = await $api.addTicket(params)
      loading.value = false
      if (res && res.code === 0) {
        message.success("新增成功")
        cancel()
        emits("getOrderList")
      }
    })
    .catch((error) => {
      console.log("error", error)
    })
}
const uploadUrl = async (val) => {
  return `${$api.uploadAction().url}`
}
const handleUploadChange = (data, type) => {
  if (data.file?.response?.code === 0 && data.file.status !== "removed") {
    form.value[type] = data.file.response.data.id
  }
}
const errorMsgRule = (msg) => {
  return (rule, value) => {
    if (!msg) {
      return Promise.reject("请填写其他信息")
    }
    return Promise.resolve()
  }
}
const updateValues = (indexString, data) => {
  if (!indexString) {
    return
  }
  const indexes = indexString.split(",").map(Number)
  // 遍历索引并修改 data 中相应的值
  indexes.forEach((index) => {
    const keys = Object.keys(data)
    if (keys[index] !== undefined && index !== data.length - 1) {
      // 检查索引是否有效
      data[keys[index]].value = true
    }
  })
}
const initForm = async () => {
  form.value = {
    ...props.ticketRowData,
    stationId: props.rowData?.stationId,
    workOrderSerialCode: props.rowData?.serialCode,
    companyName: props.rowData?.companyName,
    operationTime: [
      props.ticketRowData.operationStartDate,
      props.ticketRowData.operationEndDate,
    ],
  }
  delete form.value.id
  updateValues(form.value.workType, workTypeList.value)
  updateValues(form.value.hazardIdentification, harmList.value)
  updateValues(form.value.workSafetyMeasure, deviceList.value)
  updateValues(form.value.protectiveEquipment, protectEquipment.value)
  workTypeList.value[workTypeList.value.length - 1].value =
    form.value.workTypeOther
  harmList.value[harmList.value.length - 1].value =
    form.value.hazardIdentificationOther
  deviceList.value[deviceList.value.length - 1].value =
    form.value.workSafetyMeasureOther
  protectEquipment.value[protectEquipment.value.length - 1].value =
    form.value.protectiveEquipmentOther
  const ids =
    `${form.value.safetyPlanFileIds},${form.value.drawingFileIds},${form.value.otherAttachFileIds}`
      .split(",")
      .filter((item) => item !== "undefined")
      .join(",")
  if (!ids) {
    return
  }
  const fileData = await $api.fileFindByIds(ids)
  if (fileData) {
    fileList.value = fileData.data?.map((item) => {
      return [
        {
          uid: item.id,
          name: item.name,
          status: "done",
          url: item.url,
        },
      ]
    })
  }
}
const handleRemove = (type) => {
  form.value[type] = null
}
</script>

<style lang="less" scoped>
.form {
  padding: 0 40px;
  margin-top: 30px;
}
.formInput,
.formSelect {
  width: 250px;
}
.ant-form-item {
  margin-top: 20px;
}
.footerBar {
  text-align: center;
  margin-top: 30px;
}
.addEquipUpload {
  .anticon-eye {
    display: none;
  }
}
.ExclamationCircleOutlined {
  margin: 0 3px 0 2px;
}
.uploadBtn {
  padding: 0;
  span {
    text-decoration: underline;
  }
}
.tableBox {
  width: 700px;
  .checkItem {
    display: inline-block;
    width: 20%;
    height: 30px;
    line-height: 30px;
  }
}
.otherInput {
  margin: 0;
  display: inline-block;
  .ant-form-item {
    margin: 0;
  }
}
::v-deep(.ant-upload-list-text) {
  width: 250px;
}
</style>
